package com.ycl.javacore.algorithm;

import java.util.HashSet;
import java.util.Set;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/10
 * Time: 8:40 PM
 * Desc: 判断链表是否有环
 */
public class AlgoCast27 {
    /**
     * 定义单向链表
     */
    public class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * 利用hashset的方式
     *
     * @param head
     * @return
     */
    public boolean hasCycleWithHashSet(ListNode head) {
        Set<ListNode> nodeSet = new HashSet<>();
        for (ListNode p = head; p != null; p = p.next) {
            if (nodeSet.contains(p)) {
                return true;
            }
            nodeSet.add(p);
        }
        return false;
    }

    /**
     * 利用2个指针
     * 快指针   慢指针
     * 快指针 比 慢指针，快一步
     * 只要快慢指针能相遇就说明有环
     *
     * @param head
     * @return
     */
    public boolean hasCycleWith2Points(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

}
